import 'dart:io';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'DioLib.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:shared_preferences/shared_preferences.dart';

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: ('dio'),
      theme: ThemeData(primaryColor: Colors.black),
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            '通过Dio发送get和post请求',
            style: TextStyle(color: Colors.white),
          ),
        ),
        body: Btnevent(),
      ),
    );
  }
}

class Btnevent extends StatefulWidget {
  @override
  _BtneventState createState() => _BtneventState();
}

class _BtneventState extends State<Btnevent> {
  String result = '展示请求数据';
  var _storageString = '';
  // final STORAGE_KEY = 'storage_key';
  @override
  //使用SharedPreferences 对数据存储读取
  // saveString() async {
  //   //利用SharedPreferences存储数据
  //   SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  //   sharedPreferences.setString(
  //       STORAGE_KEY, '测试');
  //   //获取存在SharedPreferences中的数据
  //   print(sharedPreferences.get(STORAGE_KEY));
  // }
  /**
   * 利用文件存储数据
   */
  saveString() async {
    final file = await getFile('file.text');
    //写入字符串
    file.writeAsString('测试内容');
  }

  /**
   * 获取存在文件中的数据
   */
  Future getString() async {
    final file = await getFile('file.text');
    var filePath = file.path;
    setState(() {
      file.readAsString().then((String value) {
        _storageString = value + '\n文件存储路径：' + filePath;
      });
    });
  }

  /**
   * 初始化文件路径
   */
  Future<File> getFile(String fileName) async {
    final fileDirectory = await getApplicationDocumentsDirectory();
    print(fileDirectory);
    //获取存储路径
    final filePath = fileDirectory.path;

    //或者file对象（操作文件记得导入import 'dart:io'）
    return new File(filePath + "/" + fileName);
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: Column(
        children: [

          FlatButton(
            color: Colors.blue,
            highlightColor: Colors.blue[700],
            colorBrightness: Brightness.dark,
            splashColor: Colors.grey,
            child: Text("点击发送get请求"),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            onPressed: () {
              sendRequest('/index/rightFloatAdvert', Method.get, {'data': 1})
                  .then((value) {
                setState(() {
                  result = 'Get請求：${value}';
                });
              }).catchError((error) {
                if (error) {
                  print(error.toString());
                }
              });
            },
          ),
          SizedBox(
            height: 10.0,
          ),
          FlatButton(
            color: Colors.blue,
            highlightColor: Colors.blue[700],
            colorBrightness: Brightness.dark,
            splashColor: Colors.grey,
            child: Text("点击发送post请求"),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            onPressed: () {
              sendRequest('/index/rightFloatAdvert', Method.post, {'data': 1})
                  .then((value) {
                setState(() {
                  result = 'Post請求：${value}';
                });
              }).catchError((error) {
                if (error) {
                  print(error.toString());
                }
              });
            },
          ),

          SizedBox(
            height: 10.0,
          ),
          FlatButton(
            color: Colors.blue,
            highlightColor: Colors.blue[700],
            colorBrightness: Brightness.dark,
            splashColor: Colors.grey,
            child: Text("下载文件"),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            onPressed: () {
              sendRequest('/index/rightFloatAdvert', Method.down,
                  {'savePath': './aa.html'}).then((value) {
                setState(() {
                  result = '文件下载：${value}';
                });
              }).catchError((error) {
                if (error) {
                  print(error.toString());
                }
              });
            },
          ),
          SizedBox(
            height: 10.0,
          ),
          FlatButton(
            color: Colors.blue,
            highlightColor: Colors.blue[700],
            colorBrightness: Brightness.dark,
            splashColor: Colors.grey,
            child: Text("文件操作"),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.0)),
            onPressed: () {
              saveString();
            },
          ),
          Container(
            child: Text('${this.result}'),
          ),
        ],
      ),
    );
  }
}
